package cn.xwj.Nettytest.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;

/**
 * Created by thinkjoy on 2017/6/16.
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {

//    每一次收到消息时触发
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
//       收到消息打印输出
        System.out.println(channelHandlerContext.channel().remoteAddress()+"Say:"+s);
//        给客户端返回已收到消息
        channelHandlerContext.writeAndFlush("Received your message !\n");
    }

//    当连接活跃(建立)的时候触发.输出消息源的远程地址并返回欢迎消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("RamoteAddress : "+ctx.channel().remoteAddress()+" active!");
        ctx.writeAndFlush("Welcome to "+ InetAddress.getLocalHost().getHostName()+"service!\n");
        super.channelActive(ctx);
    }
}
